package jmine.tec.web.wicket.converter;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

import org.apache.wicket.util.convert.ConversionException;
import org.apache.wicket.util.convert.IConverter;

/**
 * Converter de {@link BigDecimal}.
 * 
 * @author fernando.chovich
 * @created Apr 8, 2010
 */
public class BigDecimalConverter implements IConverter {

    private static final int TRES = 3;

    private static final int TREZENTOS_E_QUARENTA = 340;

    /**
     * {@inheritDoc}
     */
    public String convertToString(Object bigDecimal, Locale locale) {
        final DecimalFormat format = new DecimalFormat("#0.#");
        format.setParseIntegerOnly(false);
        format.setParseBigDecimal(true);
        format.setGroupingSize(TRES);
        format.setGroupingUsed(true);
        format.setMaximumFractionDigits(TREZENTOS_E_QUARENTA);
        format.setDecimalFormatSymbols(new DecimalFormatSymbols(new Locale("pt", "BR")));
        final BigDecimal number = (BigDecimal) bigDecimal;
        if (number.scale() > 0) {
            format.setMinimumFractionDigits(2);
        }
        return format.format(bigDecimal);
    }

    /**
     * {@inheritDoc}
     */
    public Object convertToObject(String value, Locale locale) {
        try {
            return (value == null) || value.length() == 0 ? null : new BigDecimal(this.formatString(value));
        } catch (NumberFormatException e) {
            throw new ConversionException(e);
        }
    }

    /**
     * Formata uma string como bigdecimal
     * 
     * @param value value
     * @return string formatada
     */
    private String formatString(String value) {
        return value.replaceAll("\\.", "").replace(',', '.');
    }
}
